<template>
   <div class="pay">
        <wxc-minibar title="支付">
            <!-- <div class="header-con" slot="middle">
                <text class="header-title">支付</text>
            </div> -->
        </wxc-minibar>
        <div class="paytitle">
           <text style="font-family: PingFangSC-Medium;font-size: 28px;color: #666666;">{{currentTitle}}</text>
        </div>
        <div class="paymoney">
           <div class="paymoney_first">
             <div class="paymoney_first_fl">
                 <text style="font-family: PingFangSC-Medium;font-size: 32px;color: #333333;">订单金额</text>
             </div>
             <div class="paymoney_first_fr">
                <text style="font-size: 32px;color: #444444;">{{money}}元</text>
             </div>
           </div>           
			<!-- !!this.order -->

			<div class="paymoney_first"  v-if="!!order && getUrlDate.operation != 'modifyGuaranteeUp'">
                <div class="paymoney_first_fl">
                    <text style="font-family: PingFangSC-Medium; font-size:32px; color:#c9c9c9;">优惠券折扣</text>
                </div>
                <div style="margin-right: 32px;">
                    <text style="font-family: PingFangSC-Medium; font-size:32px; color:#c9c9c9;">-{{baseCoupon}}元</text>
                </div>
           </div>

           <div class="paymoney_first" @click="linkRouter()" v-if="!order && getUrlDate.operation != 'modifyGuaranteeUp'">
				<div class="paymoney_first_fl">
					<text style="font-family: PingFangSC-Medium;font-size: 32px;color: #333333;">优惠券折扣</text>
				</div>
				<div style="margin-right: 32px;">
					<text style="font-family: PingFangSC-Medium;font-size: 32px;color: #E70D0D;">-{{baseCoupon}}元</text>
				</div>
           </div>

           <div class="paymoney_total">
              <text style="font-family: PingFangSC-Medium;font-size: 32px;color: #333333;">共计{{ curMoney(money, baseCoupon) }}元</text>
           </div>
        </div>
        <div class="paytitle">
           <text style="font-family: PingFangSC-Medium;font-size: 28px;color: #666666;">选择支付方式</text>
        </div>
        <div class="choosedpay" @click="choosepaymodel">
            <div class="choosedpay_fl">
              <image style="width:40px;height:34px;margin-right:32px;" src="http://zhongcai-test.oss-cn-beijing.aliyuncs.com/hch5/paymodel.png"></image>
              <text style="font-family: PingFangSC-Medium;font-size: 32px;color: #333333;">支付方式</text>
            </div>
            <div class="choosedpay_fr">
               <text style="font-size: 28px;color: #666666;font-family: PingFangSC-Medium;">{{paymodel.title}}</text>
				<text class="discover_item_arrow">&#xe61c;</text>
            </div>
        </div>
        <div class="gopay">
           <div class="gopay_button" @click="getOrder()">
               <text style="font-family: PingFangSC-Medium;font-size: 32px;color: #FFFFFF;">立即购买</text>
               <text style="font-family: PingFangSC-Medium;font-size: 32px;color: #FFFFFF;">￥{{ curMoney(money, baseCoupon)  }}元</text>
           </div>
        </div>
         <wxc-popup popup-color="#FFFFFF"
               :show="isBottomShow"
               @wxcPopupOverlayClicked="popupOverlayBottomClick"
               pos="bottom"
               height="700">
            <div class="paylist">
                <div class="paylist_title">
                    <text style="font-family: PingFangSC-Medium;font-size: 32px;color: #333333;">选择支付方式</text>
                </div>
                <div class="pay_detail" @click="qiehuancheck(item)" v-for="(item,index) in paymodellist" :key="index+1/17" >
                   <div class="pay_detail_fl">
                       <image style="width:40px;height:40px;" :src="item.src"></image>
                       <text style="font-family: PingFangSC-Medium;font-size: 32px;color: #333333;margin-left:32px;">{{item.title}}</text>
                   </div>
                   <div class="pay_detail_fr">
                      <div v-if="!item.checkflag" style="width:40px;height:40px;background-color:white;border-radius:50px;border-width:1px;border-color:rgba(0,0,0,0.1);"></div>
                      <image v-if="item.checkflag" style="width:40px;height:40px;" src="http://zhongcai-test.oss-cn-beijing.aliyuncs.com/hch5/checked.png"></image>
                   </div>
                </div>
            </div>
        </wxc-popup>
        <inputkey :isBottomShow="popupShow" :closeState="false" closeTitle="取消支付" @inputVal="inputVal" @closePop="closePop"  :inputstyle="inputstyle" :textstyle="textstyle" :type="true" placeholder="支付密码:"></inputkey>
        <!-- <wxc-loadingsp :show="loadingshow" type="custom" :need-mask="true" loading-text="加载中..." m-url="http://img.alicdn.com/tfs/TB1Ep_9NVXXXXb8XVXXXXXXXXXX-74-74.gif" m-width="200" m-height="200" m-backgroundcolor="#212021" m-textcolor="#ffffff">
    </wxc-loadingsp> -->
	 <loading-big v-if="loadingshow"></loading-big>

   </div>
</template>

<script>
import { postResponsesToken } from "@/api.js";
import { WxcPopup } from "weex-ui";
import WxcLoadingsp from "../../components/modules/loading";
import inputkey from "../../components/modules/inputkey";
import { serialize, getBaseUrl, jsonAnalysis } from "@/utils/index.js";
import WxcMinibar from "@/components/modules/wxc-minibar/index.js";
import loadingBig from "@/components/modules/loading-big";
import { recentBuyGroup } from "@/js/global/index_data.js"


const navigator = weex.requireModule("navigator");
const storage = weex.requireModule("storage");
var sxglobalEvent = weex.requireModule("globalEvent");
const modal = weex.requireModule("modal");
let discountCoupon = new BroadcastChannel('discountCoupon')

export default {
	data() {
		return {
			pageType: "",
			baseURL:'',
			inputstyle: {
				width: "550px",
				height: "50px",
				marginTop: "0px",
				marginBottom: "0px",
				marginLeft: "auto",
				marginRight: "auto",
				fontSize: "30px"
			},
			textstyle: {
				fontSize: "30px",
				fontWeight: "600",
				color: "#999",
				letterSpacing: "10px",
				marginLeft: "11px"
			},
			password: "",
			popupShow: false,
			loadingshow: false,
			capitalBalance: 0,
			lottoId: "",
			order: '',
			currentTitle: "正在获取",
			money: 0,
			discounts: 0,
			paymodel: {},
			isBottomShow: false,
			changeChipCallbak: null,
			hasPayPassword:"",
			discountCouponDate:'',
			paymodellist: [
				{
					src:"http://zhongcai-test.oss-cn-beijing.aliyuncs.com/hch5/balance.png",
					title: "余额支付",
					checkflag: false,
					disabled: false,
					type: "balance"
				},
				{
					src:"http://zhongcai-test.oss-cn-beijing.aliyuncs.com/hch5/zhifubao_1.png",
					title: "支付宝支付",
					type:"alipay",
					checkflag: false,
					disabled: false
				},
				{
					src:
						"http://zhongcai-test.oss-cn-beijing.aliyuncs.com/hch5/weixin_1.png",
					title: "微信支付",
					type:"wechat",
					checkflag: false,
					disabled: false
				},
				{
					src:"http://zhongcai-test.oss-cn-beijing.aliyuncs.com/hch5/op.png",
					title: "易宝支付",
					type:'yop',
					checkflag: false,
					disabled: false
				}
			],

			getUrlDate:{},
			baseCoupon:0,
			orderState:false,
			orderOff:false
		}
	},

	components: {
		WxcPopup,
		WxcLoadingsp,
		WxcMinibar,
		inputkey,
		loadingBig
	},

	mounted() {
		this.getUrlParam();
		this.myWallet();
		this.addListtenerPayInfo()

		this.baseURL = getBaseUrl(weex.config.bundleUrl, true)

		discountCoupon.onmessage =  (event)=> {
			this.toFn()
        }
	},

	destroyed() {
		sxglobalEvent.removeEventListener("payInfo");
	},
	
	fliters:{
		fliterMoney(value) {
			// 根据订单初始状态（是否有订单号，处理是否可以使用优惠券）
			if(!this.orderState) {
				return value - this.baseCoupon > 0 ? value - this.baseCoupon : 0
			} else {
				return value
			}
		}
	},
	
	methods: {

		// 刷新后退操作 //优惠券
		async toFn() {
			//优惠券
			let data = await this.getStorage('discountCoupon')
			let values = JSON.parse(data.data)

			this.baseCoupon = values.money
			this.couponRelationNos = values.id

		},
		// 路由跳转
		linkRouter() {
			// serialize 
			let param = {
				id:this.couponRelationNos,
				castMoney: this.getUrlDate['money'],
				lotteryCode: this.getUrlDate['lotteryNo']
			}
			
			if( this.pageType == 'ParticipateChipped' || this.pageType == 'sponsorChipped') {
				param.castMoney = this.getUrlDate['buyMoney'] || this.getUrlDate['totalmoney']
			}

			if( this.pageType == 'changeChip') {
				param.castMoney = this.getUrlDate['totalmoney']
			}
			
			navigator.push({
				url: this.baseURL + "views/couponlist/usecoupon.js?"+ serialize(param),
				animated: "true"
			});

		},
		// 金额过滤计算
		curMoney(accountMoney, discounts) {
			// 根据订单初始状态（是否有订单号，处理是否可以使用优惠券）
			if( this.getUrlDate.operation != 'modifyGuaranteeUp' ) {
				return accountMoney - discounts > 0 ? accountMoney - discounts : 0
			} else {
				return accountMoney
			}
			
			// if(!this.orderState) {
				
			// } else {
			// 	return accountMoney
			// }

		},
		// 三方支付
		addListtenerPayInfo() {
			//三方支付 监听
			sxglobalEvent.addEventListener("payInfo", params => {

				let { resultStatus , thirdType, msg} = params

				// 支付宝微信跳转
				this.payResult( ( thirdType === "alipay" &&  resultStatus === "9000") || ( thirdType === "wechat" && resultStatus === "0" ), params)

				( thirdType === "alipay" &&  resultStatus === "9000") || ( thirdType === "wechat" && resultStatus === "0" ) && modal.toast({ message: msg })
			})
		},
		
		// 回调成功后或者失败
		payResult(state, params) {
			!!state ? this.paySuccess() : this.payError(params)
		},
		
		// 成功
		paySuccess() {
			navigator.push({
				url: this.baseURL + "views/pay/paysuccess.js",
				animated: "true"
			});
		},

		// 失败
		payError(params) {
			modal.alert({ message: JSON.stringify(params.msg) });
		},
		
		// 唤起支付宝
		gopayalipay(name) {
			//跳转到 支付宝支付，调用支付宝客户端
			weex.requireModule("eventLoginModule").payThird(name); //alipay:支付宝 wechat.微信，yop:易宝
		},
		
		async gopaythirdresult(obj) {
			//三方支付   alipay:支付宝 wechat.微信，yop:易宝
			let reqBody = {
				type: obj.type,
				orderNo: this.order,
				detail: this.currentTitle,
				subject: this.currentTitle,
				operation: "consume",
				amount: this.curMoney(this.money, this.baseCoupon)
			}

		

			let idata = await postResponsesToken('thirdpay/pay/pay', reqBody)
			
			if (idata && idata.msg === "success") {
				let callBack = idata.data.callBack
					obj.type === 'yop' ? this.linkYop(callBack) : this.gopayalipay(obj.type + "&=@&" + callBack)
					this.loadingshow = false
				} else {
					modal.toast({ message: "发生错误，支付失败" });
					this.loadingshow = false
				}
		},
		
		linkYop(datacallback) {
			storage.setItem("webviewUrl", JSON.stringify(datacallback), event => {
				if (event.result === "success") {
					navigator.push({ 
						url: this.baseURL +"views/webview/yeepay_webview.js?type=pay&money="+ this.curMoney(this.money, this.baseCoupon),
						animated:"true"
					})
				} else {
					modal.toast({ message: "缓存跳转失败" });
				}
			})
		},

		// 生成订单号
		getOrder(){
			// 加入网速太慢，导致多个订单生成
			if(!!this.orderOff) return ;
			this.orderOff == true;
			//如果订单号存在跳转支付
			if(!!this.order) {
				this.orderState = true
				this.orderOff = false
				this.checkPayPassExit()
				return false;
			}
			
			// 参与别人的合买
			if( this.pageType  == 'ParticipateChipped') {
				this.chippedOrder()
			} else {
				this.commonOrder()
			}

			
		},

		async chippedOrder() {

			let data = await postResponsesToken('order/bet/joinTogether', {
				schemeNo: this.getUrlDate.schemeNo,
				money: this.money.toString(),
				couponRelationNos: this.couponRelationNos
			})

			if( data.code === 0) {
				this.order = data.data
				this.checkPayPassExit()
				this.orderOff = false
			} else {
				this.orderOff = false
				modal.confirm({
					message:data.msg
				})
			}
		},
		
		// 普通发起订单
		async commonOrder() {

			let param = Object.assign(this.getUrlDate,{ couponRelationNos: this.couponRelationNos})

			
			delete param.totalmoney
			delete param.lotteryId
			delete param.lotteryLimit
			delete param.lottoId
			delete param.lottotype

			// 如果不存在生成订单
			let data = await postResponsesToken('order/bet/bet', param).catch(e=> modal.toast({messagemessage:e}))

			if( data.code === 0) {
				this.order = data.data
				this.checkPayPassExit()
				this.orderOff = false
			} else {
				this.orderOff = false
				modal.confirm({
					message:data.msg
				})
			}
		},

		// 获取数据订单数据
		getUrlParam() {
			var url = decodeURI(weex.config.bundleUrl); //取得整个地址栏
			let query1 = jsonAnalysis(url.split("?")[1]);


			this.getUrlDate = query1
			this.order = query1.order || ''

			this.pageType = query1.type;
			this.money = Number(query1.totalmoney);
			this.currentTitle = query1.lottotype;
			this.lottoId = query1.lottoId;
			
			this.getMyCoupon()


		},
		
	
		// 获取优惠券
		async getMyCoupon() { 
			let castMoney = ( this.getUrlDate.type && this.getUrlDate.type === 'sponsorChipped' ) ? ( this.money - this.getUrlDate.getUrlDate) : this.money

			let param = {page:{size:10, current:1}, type:0, castMoney: castMoney, money: this.money, lotteryCode: this.getUrlDate.lotteryNo, orderNo: this.order || '' }

			if( this.pageType == 'changeChip') {
				delete param.orderNo
			}

			let data = await postResponsesToken('account/activity/getMyCoupon', param).catch(e=> modal.toast({message:e}))
			
			if(data.code === 0) {
				if(data.data.records.length > 0) {
					this.discountCouponDate = data.data.records
					let iarr = this.discountCouponDate.filter(v=>{ if(v.checked == 1) { return v.amount}})
					iarr.forEach(v=>{
						this.baseCoupon += +v.amount
					})

					this.couponRelationNos = iarr.map(v=> v.relationNo).join(',')
				}
				
			} else {
				modal.alert({
					message: data.msg
				})
			}
		},

		// 获取缓存
		getStorage(name) {
			//获取name的缓存信息
			return new Promise((resolve, rejects) => {
				storage.getItem(name, event => {
					resolve(event);
				});
			});
		},
		
		//密码参数获取值
		inputVal(e) {
			this.password = e.inputVal;
			this.checkPayPass(this.password);
		},
		
		// 修改合买金额
		async changeChip() {
			//修改保底订单
			this.loadingshow = true;
			let reqBody = this.getUrlDate

			reqBody.totalMoney = reqBody.totalmoney
			reqBody.type = this.paymodel.type
			reqBody.orderNo = reqBody.order
			delete reqBody.totalmoney
			delete reqBody.order

			try {
				let req = await postResponsesToken('cash/maccount/operate', reqBody);

				this.loadingshow = false;
				if (req.msg === "success") {

					this.changeChip = req;
					if (this.paymodel.type === "balance") {

						navigator.push({
							url: this.baseURL + `views/pay/paysuccess.js`,
							animated: "true"
						})

						return 'balance';

					} else {
						return req.data.callBack;
					}
				}
			} catch (e) {
				this.loadingshow = false;
				modal.toast({
					message: e
				});
			}
		},
		
		// 关闭密码弹窗
		closePop(e) {
			this.popupShow = e;
			setTimeout(()=>{
                navigator.push({
                    url: this.baseURL + "views/pay/payfail.js?"+serialize({'type':'fail'}),
                    animated: "true"
                });
            },1000)
		},
		
		// 金额过滤
		roundFn(n, decimals = 0) {
			return Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`)
		},

		// 获取缓存
        getItem (name) {
            return new Promise((resolve, reject)=>{
                storage.getItem(name, event => {
                    if (event.result === "success") {
                        resolve(event.data);
                    } else {
                        reject("获取数据失败");
                    }
                })
            })
		},
		

		// 获取用户信息(钱包信息)
		async myWallet() {
			try {
				let data = await postResponsesToken('account/user/userInfo')

				if( data.code === 0) {
					let { capitalAvailable } = data.data
					this.capitalBalance = capitalAvailable
					this.paymodellist[0].disabled = !capitalAvailable >= this.money
					this.paymodellist[0].checkflag = true
					this.paymodellist[0].title += "(" + capitalAvailable + ")元"
					this.paymodel = this.paymodellist[0]

				} else {
					modal.toast({ message: data.msg });
				}

			} catch (e) {
				modal.toast({ message: JSON.stringify(e) });
			}
		},

		
		
		//查询交易密码是否存在
		async checkPayPassExit() {
			// yop
			if(this.paymodel.type !== 'balance' && this.pageType === 'changeChip'){
				let chip_callBack  =  await this.changeChip();
				this.paymodel.type === 'yop' ? this.linkYop(chip_callBack) : this.gopayalipay(this.paymodel.type + "&=@&" + chip_callBack);
				return;
			}

			
			if( this.paymodel.type !== "balance" && this.pageType !== 'changeChip')  this.gopaythirdresult(this.paymodel);
		
		
			// 余额支付
			if (this.paymodel.type === "balance") {



					if (this.capitalBalance < this.curMoney(this.money, this.baseCoupon)) {
						return modal.alert({ message: "账户余额不足", okTitle: "确定" });
					}
					
					try {
						let token = await this.getStorage("token");
						if (token.data === "undefined") {
							modal.toast({ message: "用户未登录" });
							navigator.push({
								url: this.baseURL + `views/login/login.js?`,
								animated: "true"
							});
							return;
						}

						 this.getItem('personalDetails').then( (value) => {
							let { hasPayPassword } = JSON.parse(value)

							if (hasPayPassword == 1) {
								//用户有交易密码并弹出输入
								this.popupShow = true;
							} else {
								navigator.push({
									url: this.baseURL + `views/my-account/set-password.js`,
									animated: "true"
								})
							}
						})
			
						

					} catch (e) {
						this.loadingshow = false;
						modal.toast({ message: e });
					}
			}
		},
		
		// 验证密码
		async checkPayPass(payPass) {
			try {
				this.loadingshow = true

				let req = await postResponsesToken('account/user/verifyPayPassword', { payPassword: payPass })

				if (req.data === true) {
					this.loadingshow = false

					if (this.pageType === "changeChip") {
						this.changeChip();
						return;
					}
					
					this.gopayresult()
				
				} else {
					this.loadingshow = false
					modal.toast({ message: req.msg })
				}
			} catch (e) {
				this.loadingshow = false;
				modal.toast({ message: data.msg});
			}
		},
		
		// 余额支付
		async gopayresult() {
			this.loadingshow = true;

			let reqBody = {
				orderNo: this.order,
				detail: this.currentTitle,
				lotteryNo: recentBuyGroup[this.lottoId - 1].typeName,
				money: this.money
			}

			try {
				let req = await postResponsesToken('cash/maccount/consume', reqBody);
				this.loadingshow = false;
				if (req && req.msg === "success") {
					navigator.push({
						url: this.baseURL + `views/pay/paysuccess.js`,
						animated: "true"
					});
				} else {
					modal.toast({ message: "发生错误，支付失败" });
				}
			} catch (e) {
				this.loadingshow = false;
			}
		},
		
		// 回退操作
		async router() {
			navigator.pop();
		},
		
		// 选择支付方式
		popupOverlayBottomClick() {
			this.isBottomShow = false;
		},
		
		// 余额支付不足提示
		qiehuancheck(item) {
			if (item.disabled === true) {
				return modal.alert({
					message: "余额不足，请选择其他支付方式",
					okTitle: "确定"
				});
			}

			this.isBottomShow = false;
			this.paymodel = item;
		},

		//唤起支付方式
		choosepaymodel() {
			this.isBottomShow = true;
		},

	}
};
</script>
<style scoped>
.checkDiabled {
  opacity: 0.4;
}
.pay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #f5f5f5;
}
.gopay {
  position: absolute;
  left: 0;
  width: 750px;
  bottom: 60px;
  height: 96px;
  padding-left: 32px;
  padding-right: 32px;
}
.gopay_button {
  background-color: #e70d0d;
  display: flex;
  height: 96px;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  border-radius: 4px;
}
.paytitle {
  width: 750px;
  margin-top: 32px;
  margin-bottom: 16px;
  padding-left: 32px;
  display: flex;
  justify-content: center;
}
.paymoney_first {
  background-color: white;
  height: 112px;
  display: flex;
  justify-content: space-between;
  flex-direction: row;
  align-items: center;
  border-bottom-width: 1px;
  border-bottom-color: rgb(245, 245, 245);
  border-bottom-style: solid;
}
.paymoney_second {
  height: 112px;
  display: flex;
  justify-content: space-between;
}
.paymoney_total {
  height: 112px;
  display: flex;
  flex-direction: row-reverse;
  justify-content: space-between;
  align-items: center;
  padding-right: 32px;
  background-color: white;
}
.paymoney_first_fl {
  margin-left: 32px;
}
.paymoney_first_fr {
  margin-right: 32px;
}

.choosedpay {
  display: flex;
  justify-content: space-between;
  height: 112px;
  background-color: white;
  flex-direction: row;
  align-items: center;
}
.choosedpay_fl {
  align-items: center;
  margin-left: 32px;
  display: flex;
  flex-direction: row;
}
.choosedpay_fr {
  display: flex;
  flex-direction: row;
  margin-right: 32px;
  align-items: center;
}
.paylist_title {
  height: 112px;
  line-height: 112px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-bottom-width: 1px;
  border-bottom-style: solid;
  border-bottom-color: rgba(0, 0, 0, 0.1);
}
.pay_detail {
  border-bottom-width: 1px;
  border-bottom-style: solid;
  border-bottom-color: rgba(0, 0, 0, 0.1);
  height: 96px;
  line-height: 96px;
  align-items: center;
  display: flex;
  justify-content: space-between;
  flex-direction: row;
}
.pay_detail_fl {
  display: flex;
  flex-direction: row;
  margin-left: 32px;
}
.pay_detail_fr {
  margin-right: 32px;
}

.header-title {
  font-size: 34px;
  color: #fff;
  font-weight: 600;
  font-family: PingFangSC-Medium;
}

.discover_item_arrow {
  font-family: iconfttf;
  font-size: 26px;
  color: #d8d8d8;
  margin-left: 19px;
}
</style>